import {
    Card,
    Space,
    Tabs,
    Button,
    Modal, InputNumber, Form, Input, message, Spin,
} from 'antd';

import {useState, useMemo, useRef, useEffect} from 'react';
import Content from './Content/Content.jsx';
import {useLocation, useNavigate} from 'react-router-dom';
import {SwapRightOutlined} from "@ant-design/icons";
import ShowChapterDialog from "./ShowChapterDialog/index.jsx";

const {TextArea} = Input;
import {addChapterAPI, getChapterAPI, getChapterEventAPI, updateChapterAPI} from "../../../apis/novel.js";

const NovelCreationDetail = () => {

    const navigate = useNavigate();
    const location = useLocation();

    // 已保存的内容
    const [savedContentData, setSavedContentData] = useState('狂风扑面，星宿仙尊的长发在脑后飞扬。她眉头微皱，深邃的眼眸中，此刻倒映着天庭的景象。在她的记忆中，天庭还从未有过这样的狼狈。');

    // 当前 tab 索引
    const [currentTab, setCurrentTab] = useState(1);

    // tab改变
    const changeTab = (key) => {
        console.log(key);
        setCurrentTab(key);
    };

    // 新增章节数据
    const [addChapterInfo, setAddChapterInfo] = useState({
        startIndex: 1,
        endIndex: 10,
    });


    // 额外要求
    const [detail, setDetail] = useState('');

    // 新增章节
    const addChapter = async () => {
        setIsAddChapterLoading(true)

        let data = {
            role: 'user',
            startIndex: addChapterInfo.startIndex,
            endIndex: addChapterInfo.endIndex,
            bookId: location.state.novelInfo.bookId,
            detail
        }
        console.log(data);
        let res = await addChapterAPI(data);
        console.log('生成章节', res)
        if (res.code === '0000') {
            setCharacterList(res.data)
            getChapter()
            message.success('新增章节成功')
        }else {
            message.error(res.msg || '新增章节失败')
        }

        showChapterDialog.current.toggleShowChapterDialog(true)
        setIsAddChapterLoading(false)
        setIsModalOpen(false);
    }


    // 控制Modal显示状态的state
    const [isModalOpen, setIsModalOpen] = useState(false);


    const handleCancel = () => {
        setIsModalOpen(false);
    };

    // 章节数据
    const [characterList, setCharacterList] = useState([])


    // 生成的章节目录
    const [generatedChapterList, setGeneratedChapterList] = useState([])


    // 修改章节名
    const modifyChapterName = async (e) => {
        let data = {
            bookId: location.state.novelInfo.bookId,
            chapterId: window.localStorage.getItem('chapterId'),
            headline: e.target.value
        }
        let res = await updateChapterAPI(data)
        console.log('修改章节名', res)
        if (res.code === '0000') {
            message.success('修改章节标题成功')
            getChapter()
        } else {
            message.error('修改章节标题失败')
        }
    }

    // 使用useMemo优化Tabs的items生成
    const tabItems = useMemo(() => generatedChapterList.map((_, i) => {

        return {
            label: <Input value={_.headline} onFocus={() => {
                window.localStorage.setItem('sort', _.sort)
                window.localStorage.setItem('chapterId', _.chapterId)
                window.localStorage.setItem('headline', _.headline)
            }
            } onChange={modifyChapterName}/>,
            key: _.chapterId,
            children: <Content savedContentData={() => {
                return <>
                </>
            }}></Content>
        };
    }), [generatedChapterList]);

    // 显示生成的章节的弹窗对象
    const showChapterDialog = useRef(null);


    // 获取书籍章节
    const getChapter = async () => {
        let res = await getChapterAPI(location.state.novelInfo.bookId);
        console.log('章节', res.data.list)
        if (res.code === '0000') {
            setGeneratedChapterList(res.data.list)

            message.success('获取章节成功')
        } else {
            message.error('获取章节失败')
        }
    }

    useEffect(() => {
        getChapter()
    }, []);


    // 当前操作情节的索引
    const [chapterIndex, setChapterIndex] = useState(0)

    // 是否在添加章节
    const [isAddChapterLoading, setIsAddChapterLoading] = useState(false)

    return (
        <>
            {/*封装新增章节Modal组件*/}

                <Modal title="新增章节" okText="确认" cancelText="取消" open={isModalOpen} onOk={addChapter}
                       onCancel={handleCancel}>
                    <Spin spinning={isAddChapterLoading}>
                    <Space size={'middle'}>

                        <Form.Item label={'从'}>
                            <InputNumber onChange={(e) => {
                                //    修改新增章节信息
                                setAddChapterInfo({
                                    ...addChapterInfo,
                                    startIndex: e,
                                })
                            }} suffix={'章'} min={1} max={10} value={addChapterInfo.startIndex}/>
                        </Form.Item>
                        <SwapRightOutlined/>
                        <Form.Item label={'到'}>
                            <InputNumber onChange={(e) => {
                                //    修改新增章节信息
                                setAddChapterInfo({
                                    ...addChapterInfo,
                                    endIndex: e,
                                })
                            }} suffix={'章'} min={1} max={10} value={addChapterInfo.endIndex}/>
                        </Form.Item>
                    </Space>


                    <Form.Item label={'额外要求'}>
                        <TextArea
                            placeholder="额外要求"
                            autoSize={{
                                minRows: 2,
                            }}
                            value={detail}
                            onChange={(e) => setDetail(e.target.value)}
                        />
                    </Form.Item>

                    </Spin>
                </Modal>



            <ShowChapterDialog getChapter={getChapter} reAddChapter={addChapter} chapterList={characterList}
                               ref={showChapterDialog}/>

            <Card
                title={location.state.novelInfo.bookName}
                extra={
                    <Space>
                        <Button type='primary' onClick={() => setIsModalOpen(true)}>新增章节</Button>
                        <Button type='primary' onClick={() => {
                            navigate('/workplace/NovelCreation')
                        }}>返回书架</Button>
                    </Space>
                }
                style={{
                    width: '100%',
                }}
            >
                <Tabs
                    activeKey={currentTab}
                    onChange={changeTab}
                    tabPosition={'left'}
                    items={tabItems}
                />
            </Card>
        </>
    );
};

export default NovelCreationDetail;